package cn.com.zcode.exam.service;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.com.zcode.core.util.ObjectUtil;
import cn.com.zcode.core.util.PdfUtil;
import cn.com.zcode.exam.model.Option;
import cn.com.zcode.exam.model.Question;

public class ImportServiceImpl implements ImportService {
	private static Pattern quePattern = Pattern.compile("^\\d+\\W+.*");
	private static Pattern optPattern = Pattern.compile("^[A-Z]{1}\\W+.*");
	private static Pattern anwPattern = Pattern.compile("^\\d+\\W+.*答案.*");
	private static Pattern answerOption = Pattern.compile("答案\\W*[A-Z]([\\pP‘’“”])?");
	private static Pattern indexPattern = Pattern.compile("^\\d+");
	private static Pattern indexOption = Pattern.compile("^\\w{1}");

	private static String replace_anwswer = "^\\d+\\W\\s*答案\\W*[A-Z]([\\pP‘’“”])?";
	private static String replace_quest = "^\\d+\\W(\\s)*";
	private static String replace_option = "^\\w+\\W(\\s)*";

	private List<Question> loadAnswer(String string, String... exped) {

		string = this.filterString(string, exped);
		String[] abc = string.split("\n");
		StringBuffer corrstr = null;
		List<Question> list = new ArrayList<Question>();
		int length = abc.length;
		for (int i = 0; i <= length; i++) {
			String str = (i == length) ? (corrstr + "") : abc[i];
			if ((str = str.trim()).length() > 1) {
				if (anwPattern.matcher(str).matches()) {
					if (corrstr != null) {
						String corr = corrstr.toString();
						Question question = new Question();
						question.setNo(getQuestNo(corr));
						String answer = getAnswerNo(corr);
						corr = corr.replaceFirst(replace_anwswer, "").trim();
						question.setAnswer(answer);
						question.setAnalysis(corr);
						System.out.println(question);
						list.add(question);
					}
					corrstr = new StringBuffer();
				}
				if (corrstr != null) {
					corrstr.append(str);
				}

			}
		}
		return list;
	}

	private String filterString(String string, String[] exped) {
		if (exped != null) {
			for (String exstr : exped) {
				if ((exstr = exstr.trim()).length() > 1) {
					string = string.replaceAll(exstr, "");
				}
			}
		}
		return string;
	}

	public List<Question> loadQuestions(String string, String... exped) {

		string = filterString(string, exped);
		String[] abc = string.split("\n");
		LinkedList<Question> list = new LinkedList<Question>();
		Question question = null;
		StringBuffer sbquestion = null;
		StringBuffer sboption = null;
		int length = abc.length;
		for (int i = 0; i <= length; i++) {
			String str = (i == length) ? (sboption + "") : abc[i];
			if ((str = str.trim()).length() < 1) {
				continue;
			}

			if (maybeQuestion(str)) {
				if (sboption != null) {
					addOption(question, sboption.toString());
					sboption = null;
				}
				if (sbquestion == null) {
					sbquestion = new StringBuffer();
				}

			} else if (maybeAnswer(str)) {
				if (sbquestion != null) {
					String temp = sbquestion.toString();
					int no = getQuestNo(temp);
					if (question == null || no != question.getNo()) {
						question = new Question();
						question.setNo(no);
						list.add(question);
					}
					addQuestion(question, temp);
					sbquestion = null;
				}
				if (sboption == null) {

					sboption = new StringBuffer();
				} else {
					addOption(question, sboption.toString());
					sboption = new StringBuffer();
				}
			}

			if (sbquestion != null) {
				sbquestion.append(str);
				sbquestion.append(" ");
			} else if (sboption != null) {
				sboption.append(str);
				sboption.append(" ");
			}

		}
		return list;
	}

	private boolean maybeQuestion(String str) {
		return quePattern.matcher(str).matches();

	}

	private boolean maybeAnswer(String str) {

		boolean boo = optPattern.matcher(str).matches();
		return boo;
	}

	private void addQuestion(Question question, String sb) {
		sb = sb.replaceFirst(replace_quest, "");

		if (question.getEnSummary() == null) {
			question.setEnSummary(sb);
		} else {
			question.setCnSummary(sb);
		}

	}

	private void addOption(Question quest, String danstr) {
		String no = getOptionNo(danstr);
		Option option = quest.getOption(no);
		if (option == null || !no.equals(option.getNo())) {
			option = new Option();
			option.setNo(no);
			quest.addOption(option);

		}
		danstr = danstr.replaceFirst(replace_option, "");
		if (option.getEnSummary() == null) {
			option.setEnSummary(danstr);
		} else {
			option.setCnSummary(danstr);

		}
	}

	private String getAnswerNo(String str) {
		Matcher matcher = answerOption.matcher(str);
		if (matcher.find()) {
			String answer = matcher.group();
			return answer.replaceAll("[^A-Z]", "");
		}
		return null;
	}

	private int getQuestNo(String str) {
		Matcher matcher = indexPattern.matcher(str);
		if (matcher.find()) {
			String key = matcher.group();
			return Integer.parseInt(key);
		}
		return -1;
	}

	private String getOptionNo(String str) {
		Matcher matcher = indexOption.matcher(str);
		if (matcher.find()) {
			return matcher.group();
		}
		return null;
	}

	
	
	  
	private List<Question> mixQuestion(List<Question> qs, List<Question> aw) {
		for (int i = 0; i < qs.size(); i++) {
			Question question = qs.get(i);
			Question answer = aw.get(i);
			String anstr = answer.getAnswer().trim();
			anstr.replaceAll("\\s", "");
			question.setAnalysis(answer.getAnalysis());
			question.setAnswer(anstr);
			String[] ops = anstr.split(",");
			for (String string : ops) {
				if ((string = string.trim()).length() > 0) {
					Option opt = question.getOption(string);
					opt.setCorrect(true);
				}
			}
		}
		return qs;
	}

	@Override
	public List<Question> importQuestions(File url_quest, File url_option, String... expstr) {
		 String qtext = PdfUtil.read(url_quest);
		 String atext = PdfUtil.read(url_option);
		return this.importQuestions(qtext, atext, expstr);
	}

	@Override
	public List<Question> importQuestions(String qtext, String atext, String... expstr) {
		List<Question> qs = this.loadQuestions(qtext, expstr);
		List<Question> aw = this.loadAnswer(atext, expstr);
		return mixQuestion(qs, aw);

	}
	
	public String getQuestionString(Question question) {
		StringBuffer sb = new StringBuffer();
		 append(sb,question.getNo()+" "+question.getCnSummary());
		 append(sb,question.getNo()+" "+question.getEnSummary());
		 for (Option opt : question.getOptions()) {
			append(sb,opt.getNo()+" "+opt.getCnSummary());
			append(sb,opt.getNo()+" "+opt.getEnSummary());
		}
		 
		 
		 append(sb,""+question.getAnswer());
		 append(sb,""+question.getAnalysis());
		 append(sb,"=============================================");
		return sb.toString();
	}
	
	private StringBuffer append(StringBuffer sb ,String str){
		sb.append(str);
		sb.append("\n");
		return sb;
	}
	public static void main(String[] args) throws Exception {
		ImportServiceImpl  service = new ImportServiceImpl ();
		String atext = PdfUtil.getText("/q1a.pdf", "q1a.txt");
		String qtext = PdfUtil.getText("/q1.pdf", "q1.txt");
		String[] arr = new String[]{ "中国项目培训的领跑者", "我们帮助优秀的你更优秀！","PMP 考试，不仅仅是拿到证书，更是项目管理理念的提升与进阶！"};
		List<Question> qs = service.loadQuestions(qtext, arr);
		List<Question> as = service.loadAnswer(atext, arr);
		System.out.println(qs.size()+","+as.size());
		List<Question> fin = service.mixQuestion(qs, as);
		System.out.println("==>"+fin.size());
		ObjectUtil.storeObject("test/入门65题", fin);
	 }
}
